/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui.textfield;

import com.camachosanchez.util.Constantes;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Rolando
 */
public class MaxLengthTextDocument extends PlainDocument {
    //Store maximum characters permitted

    private int maxChars;
    private int tipo;

    public void setMaxChars(int maxChars, int tipo) {
        this.maxChars = maxChars;
        this.tipo = tipo;
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a)
            throws BadLocationException {
        if (str != null && (getLength() + str.length() < maxChars)) {
            if (tipo == Constantes.ENTEROS && !Character.isDigit(str.charAt(str.length() - 1))) { //Permite solo números
                return;
            } else if (tipo == Constantes.CADENAS && !Character.isDigit(str.charAt(str.length() - 1)) && !Character.isLetter(str.charAt(str.length() - 1))) { //Permite letras y números
                return;
            } else if (tipo == Constantes.DECIMALES && !Character.isDigit(str.charAt(str.length() - 1)) && str.charAt(str.length() - 1) != '.') { //Permite letras y números
                return;
            } else if (tipo == Constantes.REALES && !Character.isDigit(str.charAt(str.length() - 1)) && str.charAt(str.length() - 1) != '.' && str.charAt(str.length() - 1) != '-') { //Permite letras y números
                return;
            }
            super.insertString(offs, str, a);
        }
    }
}
